<template>
  <div v-if="isVisible" class="debug-panel">
    <div class="debug-panel__header">
      <div class="debug-panel__title">
        <DebugIcon />
        调试面板
      </div>
      
      <div class="debug-panel__controls">
        <button
          :class="['debug-panel__toggle', { 'debug-panel__toggle--active': isMinimized }]"
          @click="toggleMinimize"
        >
          <MinimizeIcon v-if="!isMinimized" />
          <MaximizeIcon v-else />
        </button>
        
        <button
          class="debug-panel__close"
          @click="close"
        >
          <CloseIcon />
        </button>
      </div>
    </div>
    
    <div v-if="!isMinimized" class="debug-panel__content">
      <!-- 标签页导航 -->
      <div class="debug-panel__tabs">
        <button
          v-for="tab in tabs"
          :key="tab.id"
          :class="['debug-panel__tab', { 'debug-panel__tab--active': activeTab === tab.id }]"
          @click="activeTab = tab.id"
        >
          <component :is="tab.icon" />
          {{ tab.label }}
        </button>
      </div>
      
      <!-- 游戏状态 -->
      <div v-if="activeTab === 'game'" class="debug-panel__section">
        <div class="debug-section">
          <h4 class="debug-section__title">游戏状态</h4>
          <div class="debug-section__content">
            <div class="debug-item">
              <span class="debug-item__label">游戏时间:</span>
              <span class="debug-item__value">{{ formatGameTime(gameTime) }}</span>
            </div>
            <div class="debug-item">
              <span class="debug-item__label">游戏速度:</span>
              <span class="debug-item__value">{{ gameSpeed }}x</span>
            </div>
            <div class="debug-item">
              <span class="debug-item__label">暂停状态:</span>
              <span class="debug-item__value">{{ isPaused ? '暂停' : '运行' }}</span>
            </div>
            <div class="debug-item">
              <span class="debug-item__label">FPS:</span>
              <span class="debug-item__value">{{ fps }}</span>
            </div>
          </div>
        </div>
        
        <div class="debug-section">
          <h4 class="debug-section__title">性能监控</h4>
          <div class="debug-section__content">
            <div class="debug-item">
              <span class="debug-item__label">内存使用:</span>
              <span class="debug-item__value">{{ formatBytes(memoryUsage) }}</span>
            </div>
            <div class="debug-item">
              <span class="debug-item__label">渲染时间:</span>
              <span class="debug-item__value">{{ renderTime }}ms</span>
            </div>
            <div class="debug-item">
              <span class="debug-item__label">更新时间:</span>
              <span class="debug-item__value">{{ updateTime }}ms</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 资源状态 -->
      <div v-if="activeTab === 'resources'" class="debug-panel__section">
        <div class="debug-section">
          <h4 class="debug-section__title">资源状态</h4>
          <div class="debug-section__content">
            <div
              v-for="resource in debugResources"
              :key="resource.id"
              class="debug-item"
            >
              <span class="debug-item__label">{{ resource.name }}:</span>
              <span class="debug-item__value">
                {{ formatNumber(resource.amount) }} / {{ formatNumber(resource.capacity) }}
                ({{ formatNumber(resource.production) }}/s)
              </span>
            </div>
          </div>
        </div>
        
        <div class="debug-section">
          <h4 class="debug-section__title">快速操作</h4>
          <div class="debug-section__content">
            <div class="debug-actions">
              <button class="debug-action" @click="addResources">
                添加资源
              </button>
              <button class="debug-action" @click="clearResources">
                清空资源
              </button>
              <button class="debug-action" @click="maxResources">
                最大资源
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 事件日志 -->
      <div v-if="activeTab === 'events'" class="debug-panel__section">
        <div class="debug-section">
          <h4 class="debug-section__title">
            事件日志
            <button class="debug-clear-btn" @click="clearEventLog">
              清空
            </button>
          </h4>
          <div class="debug-section__content">
            <div class="debug-events">
              <div
                v-for="event in eventLog"
                :key="event.id"
                :class="['debug-event', `debug-event--${event.type}`]"
              >
                <span class="debug-event__time">{{ formatTime(event.timestamp) }}</span>
                <span class="debug-event__type">{{ event.type }}</span>
                <span class="debug-event__message">{{ event.message }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 控制台 -->
      <div v-if="activeTab === 'console'" class="debug-panel__section">
        <div class="debug-section">
          <h4 class="debug-section__title">控制台</h4>
          <div class="debug-section__content">
            <div class="debug-console">
              <div class="debug-console__output">
                <div
                  v-for="log in consoleLog"
                  :key="log.id"
                  :class="['debug-console__line', `debug-console__line--${log.level}`]"
                >
                  <span class="debug-console__time">{{ formatTime(log.timestamp) }}</span>
                  <span class="debug-console__level">{{ log.level.toUpperCase() }}</span>
                  <span class="debug-console__message">{{ log.message }}</span>
                </div>
              </div>
              
              <div class="debug-console__input">
                <input
                  v-model="consoleInput"
                  type="text"
                  placeholder="输入命令..."
                  @keydown.enter="executeCommand"
                />
                <button @click="executeCommand">执行</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useGameStore } from '@/stores/game'
import { useResourcesStore } from '@/stores/resources'

// 图标组件
const DebugIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5s-.96.06-1.42.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8z' })
])

const MinimizeIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M19 13H5v-2h14v2z' })
])

const MaximizeIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z' })
])

const CloseIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z' })
])

const GameIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M21,6H3A1,1 0 0,0 2,7V17A1,1 0 0,0 3,18H21A1,1 0 0,0 22,17V7A1,1 0 0,0 21,6M20,16H4V8H20V16Z' })
])

const ResourceIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4Z' })
])

const EventIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2M12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4M11,16.5L6.5,12L7.91,10.59L11,13.67L16.59,8.09L18,9.5L11,16.5Z' })
])

const ConsoleIcon = () => h('svg', { 
  viewBox: '0 0 24 24', 
  fill: 'currentColor',
  class: 'w-4 h-4'
}, [
  h('path', { d: 'M20,19V7H4V19H20M20,3A2,2 0 0,1 22,5V19A2,2 0 0,1 20,21H4A2,2 0 0,1 2,19V5C2,3.89 2.9,3 4,3H20M13,17V15H18V17H13M9.58,13L5.57,9H8.4L11.7,12.3C12.09,12.69 12.09,13.33 11.7,13.72L8.42,17H5.59L9.58,13Z' })
])

const gameStore = useGameStore()
const resourcesStore = useResourcesStore()

const isVisible = ref(false)
const isMinimized = ref(false)
const activeTab = ref('game')
const consoleInput = ref('')

// 性能监控
const fps = ref(0)
const memoryUsage = ref(0)
const renderTime = ref(0)
const updateTime = ref(0)

// 事件日志
const eventLog = ref<Array<{
  id: string
  timestamp: number
  type: string
  message: string
}>>([])

// 控制台日志
const consoleLog = ref<Array<{
  id: string
  timestamp: number
  level: string
  message: string
}>>([])

const tabs = [
  { id: 'game', label: '游戏', icon: GameIcon },
  { id: 'resources', label: '资源', icon: ResourceIcon },
  { id: 'events', label: '事件', icon: EventIcon },
  { id: 'console', label: '控制台', icon: ConsoleIcon }
]

const gameTime = computed(() => gameStore.gameTime)
const gameSpeed = computed(() => gameStore.gameSpeed)
const isPaused = computed(() => gameStore.isPaused)

const debugResources = computed(() => {
  return Object.values(resourcesStore.resources).map(resource => ({
    id: resource.id,
    name: resource.name,
    amount: resource.amount,
    capacity: resource.capacity,
    production: resource.production
  }))
})

const formatGameTime = (time: number) => {
  const days = Math.floor(time / (24 * 60 * 60 * 1000))
  const hours = Math.floor((time % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000))
  const minutes = Math.floor((time % (60 * 60 * 1000)) / (60 * 1000))
  return `${days}天 ${hours}时 ${minutes}分`
}

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString()
}

const formatNumber = (num: number) => {
  if (num >= 1e9) return (num / 1e9).toFixed(2) + 'B'
  if (num >= 1e6) return (num / 1e6).toFixed(2) + 'M'
  if (num >= 1e3) return (num / 1e3).toFixed(2) + 'K'
  return num.toFixed(0)
}

const formatBytes = (bytes: number) => {
  if (bytes >= 1e9) return (bytes / 1e9).toFixed(2) + 'GB'
  if (bytes >= 1e6) return (bytes / 1e6).toFixed(2) + 'MB'
  if (bytes >= 1e3) return (bytes / 1e3).toFixed(2) + 'KB'
  return bytes + 'B'
}

const toggleMinimize = () => {
  isMinimized.value = !isMinimized.value
}

const close = () => {
  isVisible.value = false
}

const addResources = () => {
  Object.keys(resourcesStore.resources).forEach(resourceId => {
    resourcesStore.addResource(resourceId, 1000)
  })
  addEvent('debug', '添加了1000单位所有资源')
}

const clearResources = () => {
  Object.keys(resourcesStore.resources).forEach(resourceId => {
    resourcesStore.setResource(resourceId, 0)
  })
  addEvent('debug', '清空了所有资源')
}

const maxResources = () => {
  Object.keys(resourcesStore.resources).forEach(resourceId => {
    const resource = resourcesStore.resources[resourceId]
    resourcesStore.setResource(resourceId, resource.capacity)
  })
  addEvent('debug', '设置所有资源为最大值')
}

const addEvent = (type: string, message: string) => {
  eventLog.value.push({
    id: Date.now().toString(),
    timestamp: Date.now(),
    type,
    message
  })
  
  // 限制日志数量
  if (eventLog.value.length > 100) {
    eventLog.value = eventLog.value.slice(-100)
  }
}

const clearEventLog = () => {
  eventLog.value = []
}

const addConsoleLog = (level: string, message: string) => {
  consoleLog.value.push({
    id: Date.now().toString(),
    timestamp: Date.now(),
    level,
    message
  })
  
  // 限制日志数量
  if (consoleLog.value.length > 100) {
    consoleLog.value = consoleLog.value.slice(-100)
  }
}

const executeCommand = () => {
  const command = consoleInput.value.trim()
  if (!command) return
  
  addConsoleLog('input', `> ${command}`)
  
  try {
    // 简单的命令解析
    const [cmd, ...args] = command.split(' ')
    
    switch (cmd) {
      case 'help':
        addConsoleLog('info', '可用命令: help, clear, speed <value>, pause, resume, resource <id> <amount>')
        break
        
      case 'clear':
        consoleLog.value = []
        break
        
      case 'speed':
        if (args[0]) {
          const speed = parseFloat(args[0])
          gameStore.setGameSpeed(speed)
          addConsoleLog('success', `游戏速度设置为 ${speed}x`)
        } else {
          addConsoleLog('error', '请提供速度值')
        }
        break
        
      case 'pause':
        gameStore.pauseGame()
        addConsoleLog('success', '游戏已暂停')
        break
        
      case 'resume':
        gameStore.resumeGame()
        addConsoleLog('success', '游戏已恢复')
        break
        
      case 'resource':
        if (args[0] && args[1]) {
          const resourceId = args[0]
          const amount = parseFloat(args[1])
          resourcesStore.setResource(resourceId, amount)
          addConsoleLog('success', `设置资源 ${resourceId} 为 ${amount}`)
        } else {
          addConsoleLog('error', '请提供资源ID和数量')
        }
        break
        
      default:
        addConsoleLog('error', `未知命令: ${cmd}`)
    }
  } catch (error) {
    addConsoleLog('error', `命令执行错误: ${error.message}`)
  }
  
  consoleInput.value = ''
}

// 性能监控
let lastTime = performance.now()
let frameCount = 0

const updatePerformance = () => {
  const now = performance.now()
  frameCount++
  
  if (now - lastTime >= 1000) {
    fps.value = Math.round((frameCount * 1000) / (now - lastTime))
    frameCount = 0
    lastTime = now
    
    // 更新内存使用（如果支持）
    if (performance.memory) {
      memoryUsage.value = performance.memory.usedJSHeapSize
    }
  }
  
  requestAnimationFrame(updatePerformance)
}

// 键盘快捷键
const handleKeydown = (event: KeyboardEvent) => {
  // F12 切换调试面板
  if (event.key === 'F12') {
    event.preventDefault()
    isVisible.value = !isVisible.value
  }
  
  // Ctrl+Shift+D 切换调试面板
  if (event.ctrlKey && event.shiftKey && event.key === 'D') {
    event.preventDefault()
    isVisible.value = !isVisible.value
  }
}

onMounted(() => {
  // 只在开发环境显示
  if (import.meta.env.DEV) {
    document.addEventListener('keydown', handleKeydown)
    updatePerformance()
    
    // 监听控制台输出
    const originalLog = console.log
    const originalWarn = console.warn
    const originalError = console.error
    
    console.log = (...args) => {
      originalLog(...args)
      addConsoleLog('log', args.join(' '))
    }
    
    console.warn = (...args) => {
      originalWarn(...args)
      addConsoleLog('warn', args.join(' '))
    }
    
    console.error = (...args) => {
      originalError(...args)
      addConsoleLog('error', args.join(' '))
    }
  }
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
})

// 监听游戏事件
watch(() => gameStore.gameTime, () => {
  // 可以在这里添加游戏时间变化的监控
})
</script>

<style scoped>
.debug-panel {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 400px;
  max-height: 80vh;
  background: var(--bg-modal);
  border: 1px solid var(--border-secondary);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-xl);
  backdrop-filter: blur(10px);
  z-index: var(--z-modal);
  font-size: var(--text-sm);
  overflow: hidden;
}

.debug-panel__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-sm) var(--spacing-md);
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid var(--border-primary);
}

.debug-panel__title {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-weight: 600;
  color: var(--text-primary);
}

.debug-panel__controls {
  display: flex;
  gap: var(--spacing-xs);
}

.debug-panel__toggle,
.debug-panel__close {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-sm);
  color: var(--text-muted);
  transition: all var(--transition-fast);
  cursor: pointer;
}

.debug-panel__toggle:hover,
.debug-panel__close:hover {
  color: var(--text-primary);
  background: rgba(255, 255, 255, 0.1);
}

.debug-panel__content {
  max-height: calc(80vh - 60px);
  overflow-y: auto;
}

.debug-panel__tabs {
  display: flex;
  border-bottom: 1px solid var(--border-primary);
}

.debug-panel__tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-sm);
  color: var(--text-muted);
  transition: all var(--transition-fast);
  cursor: pointer;
  font-size: var(--text-xs);
}

.debug-panel__tab:hover {
  color: var(--text-secondary);
  background: rgba(255, 255, 255, 0.05);
}

.debug-panel__tab--active {
  color: var(--primary-color);
  background: rgba(0, 212, 255, 0.1);
  border-bottom: 2px solid var(--primary-color);
}

.debug-panel__section {
  padding: var(--spacing-md);
}

.debug-section {
  margin-bottom: var(--spacing-lg);
}

.debug-section:last-child {
  margin-bottom: 0;
}

.debug-section__title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--text-sm);
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
}

.debug-section__content {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-md);
  padding: var(--spacing-sm);
}

.debug-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-xs) 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.debug-item:last-child {
  border-bottom: none;
}

.debug-item__label {
  color: var(--text-secondary);
  font-size: var(--text-xs);
}

.debug-item__value {
  color: var(--text-primary);
  font-size: var(--text-xs);
  font-family: monospace;
}

.debug-actions {
  display: flex;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
}

.debug-action {
  padding: var(--spacing-xs) var(--spacing-sm);
  background: var(--primary-color);
  color: var(--bg-primary);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  transition: all var(--transition-fast);
  cursor: pointer;
}

.debug-action:hover {
  background: var(--primary-light);
}

.debug-clear-btn {
  padding: var(--spacing-xs) var(--spacing-sm);
  background: var(--error-color);
  color: var(--text-primary);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  cursor: pointer;
}

.debug-events {
  max-height: 200px;
  overflow-y: auto;
}

.debug-event {
  display: flex;
  gap: var(--spacing-sm);
  padding: var(--spacing-xs);
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  font-size: var(--text-xs);
}

.debug-event:last-child {
  border-bottom: none;
}

.debug-event__time {
  color: var(--text-muted);
  font-family: monospace;
  min-width: 60px;
}

.debug-event__type {
  color: var(--info-color);
  min-width: 50px;
  font-weight: 500;
}

.debug-event__message {
  color: var(--text-secondary);
  flex: 1;
}

.debug-event--error .debug-event__type {
  color: var(--error-color);
}

.debug-event--warning .debug-event__type {
  color: var(--warning-color);
}

.debug-event--success .debug-event__type {
  color: var(--success-color);
}

.debug-console {
  display: flex;
  flex-direction: column;
  height: 250px;
}

.debug-console__output {
  flex: 1;
  overflow-y: auto;
  background: rgba(0, 0, 0, 0.3);
  border-radius: var(--radius-sm);
  padding: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
}

.debug-console__line {
  display: flex;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-xs);
  font-size: var(--text-xs);
  font-family: monospace;
}

.debug-console__time {
  color: var(--text-muted);
  min-width: 60px;
}

.debug-console__level {
  min-width: 50px;
  font-weight: 500;
}

.debug-console__line--log .debug-console__level {
  color: var(--text-secondary);
}

.debug-console__line--warn .debug-console__level {
  color: var(--warning-color);
}

.debug-console__line--error .debug-console__level {
  color: var(--error-color);
}

.debug-console__line--input .debug-console__level {
  color: var(--primary-color);
}

.debug-console__line--success .debug-console__level {
  color: var(--success-color);
}

.debug-console__line--info .debug-console__level {
  color: var(--info-color);
}

.debug-console__message {
  color: var(--text-primary);
  flex: 1;
}

.debug-console__input {
  display: flex;
  gap: var(--spacing-xs);
}

.debug-console__input input {
  flex: 1;
  padding: var(--spacing-xs);
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid var(--border-primary);
  border-radius: var(--radius-sm);
  color: var(--text-primary);
  font-size: var(--text-xs);
  font-family: monospace;
}

.debug-console__input button {
  padding: var(--spacing-xs) var(--spacing-sm);
  background: var(--primary-color);
  color: var(--bg-primary);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  cursor: pointer;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .debug-panel {
    width: calc(100vw - 40px);
    max-width: 400px;
  }
}
</style>